package com.example.yichuangyun.mvvm.ui.fragment;

import android.os.Bundle;

import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentBusinessRecordBinding;
import com.example.yichuangyun.model.contacts.ContactsBusinessDataModel;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.adapter.ContactsBusinessAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.view.BusinessRecordViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 联系人详情-商机记录
 */
public class BusinessRecordFragment extends BaseFragment<FragmentBusinessRecordBinding, BusinessRecordViewModel> {

    private int contactType = 1;
    private String id;
    private List<ContactsBusinessDataModel.ContactsBusinessModel> data = new ArrayList<>();
    private ContactsBusinessAdapter adapter;

    @Override
    protected BusinessRecordViewModel bindModel() {
        return getViewModel(this, BusinessRecordViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        adapter = new ContactsBusinessAdapter(mContext, data);
        binding.recyclerView.setAdapter(adapter);
    }

    @Override
    protected void lazyLoadData() {
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle != null) {
            id = bundle.getString(Constant.idKey);
            contactType = bundle.getInt(Constant.contactTypeKey);
            viewModel.getBusinessRecordList(id, contactType);
        }
    }

    @Override
    protected void initClick() {
        viewModel.contactsBusinessData.observe(this, contactsBusinessDataModel -> {
            data = contactsBusinessDataModel.getRecords();
            adapter.onRefresh(data);
        });
    }

    public static BusinessRecordFragment newInstance(String id, int contactType) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.idKey, id);
        bundle.putInt(Constant.contactTypeKey, contactType);
        BusinessRecordFragment detailsDataFragment = new BusinessRecordFragment();
        detailsDataFragment.setArguments(bundle);
        return detailsDataFragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshContactDetailsBusinessList)) {
                viewModel.getBusinessRecordList(id, contactType);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
